package service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import dao.SeckillDao;
import dao.SuccessKilledDao;
import dao.cache.RedisDao;
import dto.Exposer;
import dto.SeckillExecution;
import entity.Seckill;
import entity.SuccessKilled;
import enums.SeckillStateEnum;
import exception.RepeatKillException;
import exception.SeckillCloseException;
import exception.SeckillException;
import service.SeckillService;

// 如果不知道它是一个service，还是dao，还是controller,可以使用@Component
@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // md5盐值,用友混淆md5
    private final String slat = "dfewqr324*&^%$*$ghyuh&*%$%}k|}?:";

    // 注入Service依赖
    @Autowired
    private SeckillDao SeckillDao;

    @Autowired
    private SuccessKilledDao successKilledDao;

    @Autowired
    private RedisDao redisDao;

    @Override
    public Seckill queryById(long seckillId) {
        return SeckillDao.queryById(seckillId);
    }

    @Override
    public List<Seckill> getSeckillList() {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("start", 0);
        param.put("size", 10);
        return SeckillDao.queryAll(param);
    }

    /**
     * 根据nowTime，startTime，endTime 判断秒杀是否开启
     */
    @Override
    public Exposer exportSeckillUrl(long seckillId) {
        // 优化点：缓存优化,一致性维护建立在超时的基础上
        // 1.访问redis
        Seckill seckill = redisDao.getSeckill(seckillId);
        if (seckill == null) { // 缓存中没有
            // 2.访问数据库
            seckill = SeckillDao.queryById(seckillId);
            if (seckill == null) {
                return new Exposer(false, seckillId);
            } else {
                // 3.将数据放入redis缓存中
                redisDao.putSeckill(seckill);
            }
        }

        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }
        String md5 = getMD5(seckillId);
        return new Exposer(true, md5, seckillId);
    }

    /**
     * 使用注解控制事务方法的优点： 1.开发团队达成一致约定，明确标注事务方法的编程风格 2.保证事务方法的执行时间尽可能短,不要穿插其它网络操作:RPC/HTTP请求或者剥离到事务方法外
     * 3.不是所有的方法都需要事务，如果只有一条修改操作，只读操作不需要控制事务
     */
    /**
     * 比较md5，判断秒杀是否合法 根据userPhone和seckillId，判断是否重复秒杀
     */
    @Override
    @Transactional
    public SeckillExecution excuteSeckill(long seckillId, long userPhone, String md5)
        throws SeckillException, RepeatKillException, SeckillCloseException {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            throw new SeckillException("秒杀数据被篡改了!");
        }
        // 执行秒杀逻辑：减少库存+记录购买行为
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("seckillId", seckillId);
        param.put("killTime", new Date());
        try {
            // 开始记录购买行为
            int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
            // 唯一：seckillId, userPhone(联合主键)
            if (insertCount <= 0) {
                // 重复秒杀
                throw new RepeatKillException("重复秒杀!");
            } else {
                // 减库存，热点商品竞争
                int num = SeckillDao.reduceNumber(param);
                if (num <= 0) {
                    // 没有更新到记录，秒杀结束，rollback
                    throw new SeckillCloseException("秒杀已结束!");
                } else {
                    // 秒杀成功，commit
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
                }
            }
        } catch (SeckillCloseException e1) { // 让这两个异常能先于Exception显示的抛出
            throw e1;
        } catch (RepeatKillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // 所有编译期异常转化为运行期异常
            throw new SeckillException("seckill inner error:" + e.getMessage());
        }
    }

    /**
     * 根据id得到md5值
     * 
     * @param seckillId
     * @return
     */
    private String getMD5(long seckillId) {
        String base = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes()); // spring提供的工具类生成md5
        System.out.println(md5);
        return md5;
    }

    @Override
    public SeckillExecution excuteSeckillProcedure(long seckillId, long userPhone, String md5) {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            return new SeckillExecution(seckillId, SeckillStateEnum.DATA_REWRITE);
        }
        Date killTime = new Date();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("seckillId", seckillId);
        param.put("phone", userPhone);
        param.put("killTime", killTime);
        param.put("status", 0);
        param.put("result", null);
        // 执行存储过程，result被赋值
        try {
            SeckillDao.killByProcedure(param);
            // 获取result
            int result = MapUtils.getInteger(param, "result", -2); // 要获取result属性，没有的话给result赋-2
            if (result == 1) {
                SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
            } else {
                return new SeckillExecution(seckillId, SeckillStateEnum.stateOf(result));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new SeckillExecution(seckillId, SeckillStateEnum.INNOR_ERROR);
        }
    }
}
